<?php
/**
 * 清空日志
 * User：liujun
 * Date：2022/3/9
 * Time：8:57 PM
 */

namespace Encore\Admin\Actions\Custom;

use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\Finder\Finder;

class EmptyErrorLogAction extends Action
{
    protected $selector = '.empty-error-log-action';
    public $name = '清空日志文件';

    public function handle(Request $request): Response
    {
        @file_put_contents(storage_path('logs/' . $request->get('filename')), '');
        return $this->response()->success('日志文件清空成功!')->refresh();
    }

    public function form()
    {
        $files = collect((new Finder())
            ->in(storage_path('logs'))
            ->files())
            ->filter(function ($file) {
                return Str::contains($file, '.log');
            })
            ->map(function ($file) {
                return Str::afterLast($file, '/');
            })
            ->values()
            ->toArray();

        $this->select('filename', '选择文件')
            ->options(array_combine($files, $files))
            ->rules('required');
    }

    public function html(): string
    {
        return '<li><a href="javascript:;" class="empty-error-log-action"><i class="fa fa-trash-o"></i></a></li>';
    }
}